<?php

Loader::using("ext::libs::php::collections::Tree");

/**
 * Description of InscripcionesGenericas
 *
 *  @export Modules
 */
class InscripcionesGenericas extends Module {

    private $useTabs = false;
    private $toClient = array();
    private $respuestas = array();
    private $fieldNames = array();

    public function index() {
        $tipo = $this->request->get("formId", "1");
        /* @var $Formulario TiposFormularios */
        $Formulario = $this->model->Formularios->getFormulario($tipo);

        $this->assign("Action", $this->route->action("guardar"));
        $Tree = $this->getFieldTree($Formulario->getCamposFormularios());

        $this->assign("Tree", $Tree);
        $this->assign("Destino", $Formulario->getDestino());
        $this->assign("UseTabs", $this->useTabs);
        $this->assign("Scripts", $this->route->action("scripts", array("ajax" => "1",)));

        $this->display("index");
    }

    public function scripts() {
        $tipo = $this->request->get("formId", "1");
        /* @var $preguntas TiposFormularios */
        $preguntas = $this->model->Formularios->getFormulario($tipo);
        $Formulario = array();

        foreach ($preguntas->getCamposFormularios() as $pregunta) {
            $controlsFactory = QuestionBasedUIControlFactory::instance();
            $controlsFactory->setQuestion($pregunta);
            $controlsFactory->create();
        }

        header("Content-type: text/javascript", true);
        echo 'ModuleCall = function (app, module, task) {
                this.app = app;
                this.module = module;
                this.task = task;
            }

            AcawebAjaxRequest = function () {}
            AcawebAjaxRequest.prototype = {
                isJSON:true,
                useCache:true,
                context:null,

                beforeSend:function(){},
                success:function(){},
                error:function(){},

                invoke:function(call, urlParams, data, type){
                    var url = this.buildURL(call, urlParams);
                    console.log(url)
                    var request = {
                        url:url,
                        type: type ? type : "GET",
                        data:data
                    }
                    request.beforeSend = this.beforeSend;
                    request.success = this.success;
                    request.error = this.error;
                    request.cahce = this.useCache;

                    if(this.isJSON){
                        request.dataType = "json";
                    }
                    if(this.context){
                        request.context = this.context;
                    }

                    jQuery.ajax(request);
                },

                buildURL:function (call, params){
                    var url = String.format("{0}&controller={1}.{2}&task={3}&ajax=true", BASE_URL, call.app, call.module, call.task);
                    var paramList = "";
                    if(TypeOf(params) == "string"){
                        paramList = "&" + params;
                    } else{
                        jQuery.each(params, function(Key, Value){
                            paramList += "&" + Key + "=" + Value;
                        });
                    }

                    url += paramList;
                    return url;        
                }
            }

            Locaciones = function(){
                AcawebAjaxRequest.apply(this, arguments);
                this.moduleCall = new ModuleCall("PublicData", "Locaciones", "");
            }
            Locaciones.Extend(AcawebAjaxRequest, {
                getPaises:function (){
                    this.moduleCall.task = "getPaises";
                    this.parent.invoke.call(this, this.moduleCall);
                },

                GetMunicipio:function (CodigoDepartamento) {
                    this.moduleCall.task = "GetMunicipio";
                    this.parent.invoke.call(this, this.moduleCall, {
                        CodigoDepartamento:CodigoDepartamento
                    })
                },

                GetMunicipioByNombreDepartamento:function (NombreDepartamento) {
                    this.moduleCall.task = "GetMunicipioByNombreDepartamento";
                    this.parent.invoke.call(this, this.moduleCall, {
                        NombreDepartamento:NombreDepartamento
                    });
                },

                GetDepartamento:function (NombrePais) {
                    this.moduleCall.task = "GetDepartamento";
                    this.parent.invoke.call(this, this.moduleCall, {
                        NombrePais:NombrePais
                    });

                },

                GetDepartamentoByPais:function (IdPais) {
                    this.moduleCall.task = "GetDepartamentoByPais";
                    this.parent.invoke.call(this, this.moduleCall, {
                        IdPais:IdPais
                    });
                }
            });

            jQuery.noConflict();
            jQuery(document).ready(function($){
                $(".breadcrumb").wl_Breadcrumb({numbers:true});
            '; 
            $UsedControls = QuestionBasedUIControlFactory::instance()->getUsedTypes();
            foreach ($UsedControls as /* @var $Control UIControl */ $Control){
                echo $Control->renderScript(false);
            }

            $Constraints = ConstraintFactory::instance()->getConstraints();
            foreach ($Constraints as /* @var $Constraint Constraint */ $Constraint){
                echo $Constraint->render();
            }
            
            echo "});";
    }

    private function getFieldTree($campos) {
        $tree = new Tree("CamposFormularios");

        foreach ($campos as /* @var $campo CamposFormularios */$campo) {
            $route = explode(" > ", $campo->getGrupo());

            if (count($route) > 1) {
                $this->useTabs = true;
            }

            $tree->appendInRoute($campo, $route);
        }

        return $tree->to_array();
    }

    public function guardar() {
        if ($this->request->submitted()) {
            Loader::using("models::entities::ValoresFormularios");
            Loader::using("models::entities::Suscritos");

            $results = $this->request->post("Values", array());
            $this->fieldNames = $this->request->post("Names", array());

            foreach ($results as $key => $value) {
                $this->appendToClient($key, $value);
                $this->appendToAnswers($key, $value);
            }


            $suscrito = new Suscritos();
            $suscrito->setRespuestas($this->respuestas);
            $suscrito->setInfo($_SERVER["REMOTE_ADDR"] . ":" . $_SERVER["REMOTE_PORT"] . " - " . $_SERVER["HTTP_USER_AGENT"]);

            $this->model->Formularios->responderFormulario($suscrito);

            $this->assign("ToClient", $this->toClient);
            $this->assign("client", $this->request->post("destination"));
            $this->display();
        } else {
            $this->index();
        }
    }

    private function appendToClient($k, $v) {

        $toClientName = $this->fieldNames[$k];

        if (empty($toClientName)) {
            $toClientName = $k;
        }

        // TODO: [!] CAMBIA ESTO O TE AVERGONZARÁS TODA LA VIDA DE DECIR QUE ERES PROGRAMADOR!!!!
        if (is_array($v)) {
            foreach ($v as $index => $value) {
                if (is_array($value)) {
                    foreach ($value as $innerKey => $innerValue) {
                        $name = $this->toValidKey($toClientName . "-$index-$innerKey");
                        $this->toClient[$name] = $innerValue;
                    }
                } else {
                    $name = $this->toValidKey($toClientName . "-$index");
                    $this->toClient[$name] = $value;
                }
            }
        } else {
            $name = $this->toValidKey($toClientName);
            if (array_key_exists($name, $this->toClient)) {
                $name .= "-$k";
            }
            $this->toClient[$name] = $v;
        }
    }

    private function toValidKey($key) {
        return str_replace(
                        array(" ", "Á", "É", "Í", "Ó", "Ú", "Ñ", "á", "é", "í", "ó", "ú", "ñ"), array("", "A", "E", "I", "O", "U", "N", "a", "e", "i", "o", "u", "n"), $key);
    }

    private function appendToAnswers($k, $v) {
        $textValue = is_array($v) ? json_encode($v) : $v;

        $valor = new ValoresFormularios();
        $valor->setIdCampo($k);
        $valor->setRespuesta($textValue);

        $this->respuestas[] = $valor;
    }

}

?>
